﻿using Microsoft.Extensions.Options;
using NumericUpDownLib;
using NumericUpDownLib.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using XYAC.Framework.MonitorTireMaterialManual.Entities;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;
using XYAC.Framework.MonitorTireMaterialManual.ViewModels;
using static System.Net.Mime.MediaTypeNames;

namespace XYAC.Framework.MonitorTireMaterialManual.Views
{
    /// <summary>
    /// SemiSteelTreadScanView.xaml 的交互逻辑
    /// </summary>
    public partial class SemiSteelTreadScanView1 : UserControl
    {
        public IOptionsMonitor<AppConfig> AppConfig { get; }
        public SemiSteelTreadScanViewModel ViewModel { get; }

        private IServiceProvider provider;

        public SemiSteelTreadScanView1(IOptionsMonitor<AppConfig> appConfig, SemiSteelTreadScanViewModel viewmodel, IServiceProvider provider)
        {
            this.DataContext = this.ViewModel = viewmodel;
            this.ViewModel.CloseWindow = () =>
            {

                if (this.Parent is Window win)
                {
                    win.DialogResult = true;
                    win.Close();
                }
            };
            this.AppConfig = appConfig;
            this.provider = provider;
            InitializeComponent();
        }


        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox cmb)
            {
                if (cmb.SelectedIndex != -1)
                    this.ViewModel.CrossSectionShape = (cmb.SelectedItem as ComboBoxItem).Tag.ToString();
            }
        }

        private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox cmb)
            {
                if (cmb.SelectedIndex != -1)
                    this.ViewModel.OthoerPointsThickness_Stable = (cmb.SelectedItem as ComboBoxItem).Tag.ToString();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        internal void ClearViewModelValue()
        {
            this.ViewModel.SemiSteelTreadScanReport = null;
        }

        private void FloatUpDown_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (sender is FloatUpDown np)
            {
                if (np.IsReadOnly)
                {
                    np.IsReadOnly = false;
                    np.IsIncDecButtonsVisible = true;
                }
            }
        }

        private void FloatUpDown_KeyDown(object sender, KeyEventArgs e)
        {
            if (sender is FloatUpDown np && (e.Key == Key.Enter || e.Key == Key.Escape))
            {
                var fieldInfo = typeof(AbstractBaseUpDown<float>).GetField("_PART_TextBox", BindingFlags.NonPublic | BindingFlags.Instance);
                var sourceTxt = fieldInfo?.GetValue(np) as TextBox;
                if (float.TryParse(sourceTxt.Text, out float value))
                {
                    np.IsReadOnly = true;
                    np.IsIncDecButtonsVisible = false;
                }
                else
                {
                    //此处无法退出输入模式
                    MessageBox.Show("当前输入非法,请修正输入值后再确认退出输入模式");
                }
            }

            if (sender is NumericUpDown nup && (e.Key == Key.Enter || e.Key == Key.Escape))
            {
                var fieldInfo = typeof(AbstractBaseUpDown<int>).GetField("_PART_TextBox", BindingFlags.NonPublic | BindingFlags.Instance);
                var sourceTxt = fieldInfo?.GetValue(nup) as TextBox;
                if (int.TryParse(sourceTxt.Text, out int value))
                {
                    nup.IsReadOnly = true;
                    nup.IsIncDecButtonsVisible = false;
                }
                else
                {
                    //此处无法退出输入模式
                    MessageBox.Show("当前输入非法,请修正输入值后再确认退出输入模式");
                }
            }

        }

        private void ComboBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender is ComboBox cmb)
            {
                var text = cmb.Text;
                foreach (var item in cmb.Items)
                {
                    if (item is ComboBoxItem cmbi && text == cmbi.Content.ToString())
                    {
                        text = cmbi.Tag.ToString();
                    }
                }
                this.ViewModel.OthoerPointsThickness_Stable = text;
            }
        }

        private void ComboBox_TextChanged_1(object sender, TextChangedEventArgs e)
        {
            if (sender is ComboBox cmb)
            {
                var text = cmb.Text;
                foreach (var item in cmb.Items)
                {
                    if (item is ComboBoxItem cmbi && text == cmbi.Content.ToString())
                    {
                        text = cmbi.Tag.ToString();
                    }
                }
                this.ViewModel.OthoerPointsThickness_Scan = text;
            }
        }

        private void ComboBox_SelectionChanged_2(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox cmb)
            {
                if (cmb.SelectedIndex != -1)
                    this.ViewModel.OthoerPointsThickness_Scan = (cmb.SelectedItem as ComboBoxItem).Tag.ToString();
            }
        }

        private void ComboBox_SelectionChanged_3(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox cmb)
            {
                if (cmb.SelectedIndex != -1)
                    this.ViewModel.AntennaAdhesiveSpec_Penetration = (cmb.SelectedItem as ComboBoxItem).Tag.ToString();
            }
        }

        private void NumericUpDown_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (sender is NumericUpDown np)
            {
                if (np.IsReadOnly)
                {
                    np.IsReadOnly = false;
                    np.IsIncDecButtonsVisible = true;
                }
            }
        }

        private void NumericUpDown_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (sender is NumericUpDown np && (e.Key == Key.Enter || e.Key == Key.Escape))
            {
                np.IsReadOnly = true;
                np.IsIncDecButtonsVisible = false;
            }
        }

        #region UserId
        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 使用正则表达式检查输入是否为数字
            e.Handled = !Regex.IsMatch(e.Text, @"^\d+$");
        }

        private void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
        {
            // 获取剪贴板中的文本
            var clipboardText = e.DataObject.GetData(typeof(string)) as string;

            // 如果剪贴板中的内容不是数字，取消粘贴操作
            if (clipboardText != null && !clipboardText.All(char.IsDigit))
            {
                e.CancelCommand(); // 取消粘贴操作
            }
        }

        private void TextBox_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (sender is TextBox txt)
            {
                txt.IsReadOnly = false;
                txt.SelectAll();
            }
        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (sender is TextBox txt && (e.Key == Key.Enter || e.Key == Key.Escape))
            {
                if (txt.Text.Trim().Length == 0) return;
                txt.IsReadOnly = true;
                // 让 TextBox 失去焦点
                Keyboard.ClearFocus();
                //if (e.Key == Key.Enter)
                //{
                //    //此处用于写入正确的员工ID到配置文件
                //    this.ViewModel.UpdateUserId(txt.Text);
                //}
            }
        }
        #endregion

        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox fud = sender as TextBox;
            fud.SelectAll();
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (sender is TextBox txt)
            {
                if (txt.Text.Trim().Length == 0) return;
                this.ViewModel.UpdateUserId(txt.Text);
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            RecurseVisualTree(this, control =>
            {
                if (control is TextBox textBox)
                {
                    textBox.IsReadOnly = true;
                }
                else if (control is ComboBox comboBox)
                {
                    comboBox.IsReadOnly = true;
                    comboBox.IsEnabled = false;
                    //comboBox.SelectedIndex = 0;
                }
            });
        }
        public void RecurseVisualTree(DependencyObject root, Action<DependencyObject> action)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(root, i);
                action(child);
                RecurseVisualTree(child, action);
            }
        }
    }
}
